<?php

namespace app\common\controller;
use app\common\service\shop\Sql as SqlService;
use think\facade\Config;
use think\facade\View;
use think\facade\Db;
use think\facade\Cookie;
use app\common\service\shop\Data as DataService;

class Shop
{
    /*
    列表模板
    */
    public function Index()
    {
        $usertoken = $this->Usertoken();
        View::assign('usertoken', $usertoken);
        return ViewTpl('/common/shop/list');
    }

    public function userinfo()
    {

        $usertoken = $this->Usertoken();
        View::assign('usertoken', $usertoken);
        return View::fetch('/common/shop/userinfo');
    }

    public function Savetoken()
    {
        $time = input('token_time') - 300;
        $tt = input();
        $tt['token'] = $tt['cms_token'];
        unset($tt['cms_token']);
        $usertoken = json_encode($tt, JSON_UNESCAPED_UNICODE);
        Cookie::set('usertoken', $usertoken, $time);
        return getSuccess($usertoken);
    }

    public function Usertoken()
    {
        $usertoken = json_decode(Cookie::get('usertoken'), true);
        if (empty($usertoken['token'])) {
            $usertoken['token'] = '';
        }
        return $usertoken;
    }

    public function Udownload()
    {
        $end_zip = input('down_url');
        $down_url = 'storage/appcache/' . input('app_num') . '.zip';
        $file = $this->downloadZip($end_zip, $down_url);
        if (empty($file)) {
            return getError('下载失败');
        }
        $app_type = 'app';
        if (input('app_type') == 2) {
            $app_type = 'plugins';
        }
        if (input('app_type') == 3) {
            $app_type = 'template';
        }
        $jieya = $this->unzip_file($file, App()->getRootPath() . "addons/" . $app_type);
        if ($jieya != 2) {
            return getError('解压失败');
        }
        unlink($down_url);
        return getSuccess(input());
    }

    function unzip_file($file, $destination)
    {
        $zip = new \ZipArchive;
        if ($zip->open($file) !== TRUE) {
            return 1;
        }
        $zip->extractTo($destination);
        $zip->close();
        return 2;
    }


    public function downloadZip($url = '', $file = '', $timeout = 60)
    {
        if (file_exists($file)) {
            unlink($file);
        }
        $file = empty($file) ? pathinfo($url, PATHINFO_BASENAME) : $file;
        $dir = pathinfo($file, PATHINFO_DIRNAME);
        !is_dir($dir) && @mkdir($dir, 0777, true);
        $url = str_replace(" ", "%20", $url);
        if (function_exists('curl_init')) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $temp = curl_exec($ch);
            if (@file_put_contents($file, $temp) && !curl_error($ch)) {
                return $file;
            } else {
                return false;
            }
        } else {
            $opts = array(
                "http" => array(
                    "method" => "GET",
                    "header" => "",
                    "timeout" => $timeout)
            );
            $context = stream_context_create($opts);
            if (@copy($url, $file, $context)) {
                return $file;
            } else {
                return false;
            }
        }
    }

    //安装应用
    public function Install()
    {
        //复制文件
        $app_type = 'app';
        if (input('app_type') == 2) {
            $app_type = 'plugins';
        }
        if (input('app_type') == 3) {
            $app_type = 'template';
        }
        $apppath = App()->getRootPath() . "addons/" . $app_type . "/" . input('app_num') . "/";
        $this->xCopy(App()->getRootPath() . "addons/" . $app_type . "/" . input('app_num'), App()->getRootPath(), 1);
        if (file_exists($apppath . "ruinuo")) {
            $this->deldir(App()->getRootPath() . "ruinuo");
        }
        $sql_file = $apppath . "ruinuo/install.sql";
        if (file_exists($sql_file)) {
            //安装数据库
            $Sql = new SqlService();
            $sqlist = $Sql->getSqlFromFile($sql_file);
            if (!empty($sqlist)) {
                foreach ($sqlist as $key => $rs) {
                    $PreFix = explode('_rn_', $rs);
                    if (count($PreFix) >= 2) {
                        $mysqlPreFix = Config::get('database.connections.mysql.prefix');
                        $rs = str_ireplace($PreFix[0] . "_rn_", $mysqlPreFix . 'rn_', $rs);
                    }
                    Db::query($rs);
                }
            }
        }
        $config = array();
        if (file_exists($apppath . "ruinuo/setting.json")) {
            $config = json_decode(getBase64encode(file_get_contents($apppath . "ruinuo/setting.json")), true);
        }

        if (!empty($config)) {
            $appdata = new DataService();
            $data['config'] = $config;
            if (!empty($data['config']['set_mode'])) {
                $appdata->set_mode($data);
            }//安装应用及模块数据
            if (!empty($data['config']['set_config'])) {
                $appdata->set_config($data);
            }//安装系统配置数据
            if (!empty($data['config']['set_menu'])) {
                $appdata->set_menu($data);
            }//安装系统菜单数据
        }
        return getSuccess('', '安装成功');
    }

    //卸载应用
    public function Uninstall()
    {
        return getError('请手动卸载或者去敏捷开发=>应用管理完成卸载');
    }

//删除目录及文件
    public function deldir($dir = '')
    {
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    $this->deldir($fullpath);
                }
            }
        }
        closedir($dh);
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

//复制文件到指定目录
    public function xCopy($source, $destination, $child, $fileb = '')
    {

        if (!file_exists($destination)) {
            if (!mkdir(rtrim($destination, '/'), 0777, true)) {
                return false;
            }
            @chmod($destination, 0777);
        }

        if (!is_dir($source)) {
            return 0;
        }
        if (!is_dir($destination)) {
            mkdir($destination, 0777, true);
        }
        $handle = dir($source);
        while ($entry = $handle->read()) {
            if (($entry != ".") && ($entry != "..")) {
                if (is_dir($source . "/" . $entry)) {
                    if ($child)
                        $this->xCopy($source . "/" . $entry, $destination . "/" . $entry, $child, $fileb);
                } else {
                    if ($fileb) {
                        if (strpos($fileb, $entry) !== false) {
                            copy($source . "/" . $entry, $destination . "/" . $entry);
                        }
                    } else {
                        copy($source . "/" . $entry, $destination . "/" . $entry);
                    }
                }
            }
        }
        return 1;
    }
}
